from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from src.models import *
from django.shortcuts import HttpResponse
import time
import datetime
from src.robot.robotcontroller import RobotController
from src.parse.parsecontroller import ParseController
from src.spider.spidercontroller import SpiderController
from django.db.models import Count
import json


# Create your views here.
def register(request):
    return render(request,'register.html')

def register_form(request):
    if ('username' in request.POST) and ('password' in request.POST) and ('tel' in request.POST):
        if request.POST:
            print(request.POST['username'], request.POST['tel'], request.POST['password'])
            u1 = User(Uname=request.POST['username'],Utel=request.POST['tel'],Upassward=request.POST['password'])
            u1.save()

            return HttpResponseRedirect('/')
    else:
        error = r'请输入正确的信息'
        return render(request,'register.html',{'error':error})

def search(request):
    if 'q' in request.POST:
        goods = request.POST['q']
        sc = SpiderController(r'14786188816', r'wbydh555', goods)
        sc.session.get_Page(goods)
        pc = ParseController()
        pc.parser(goods)
    return render(request,'list.html',config_context(goods))

def config_context(goods='surface book 2'):
    context={}
    xdata = []
    ydata = []
    province = []
    for pro in Product.objects.all().filter(Pkeyword=goods):
        xdata.append(pro.Pprice)
        ydata.append(pro.Pname)
    for (name, value) in Product.objects.values_list('location').annotate(name=Count('id')):
        province.append({'name': name, 'value': value})
    context['xdata'] = json.dumps(xdata, ensure_ascii=True)
    context['ydata'] = json.dumps(ydata, ensure_ascii=True)
    context['province'] = json.dumps(province, ensure_ascii=True)
    return context


def index(request):
    return render(request,'index.html')

def list(request):
    pc = ParseController()
    if request.method == 'POST':
        if ('tel' in request.POST) and ('password' in request.POST):
            if request.POST:
                user1 = User.objects.get(Utel=request.POST['tel'])
                if user1.Upassward == request.POST['password']:
                    context = {
                        'tel': user1.Utel,
                        'username': user1.Uname,
                        'password': user1.Upassward
                    }
                    return render(request,'list.html',dict(context,**config_context()))
            else:
                return HttpResponseRedirect('/',{'error': '请输入正确的账号信息'})

def Wechat_login(request):
    rc = RobotController()
    rc.analysisSex()
    rc.analysisProvince()
    rc.analysisCity()
    return HttpResponseRedirect('/')
